package com.jw.xzg.activity;

import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;

import com.jw.xzg.R;
import com.jw.xzg.callback.JsonCallback;
import com.jw.xzg.model.ForgetPasswordModel;
import com.jw.xzg.model.SmsModel;
import com.jw.xzg.model.TokenModel;
import com.jw.xzg.model.UserModel;
import com.jw.xzg.utils.CommonUtils;
import com.jw.xzg.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;

/**
 * Created by Administrator on 2017/4/2.
 */

public class LoginActivity extends AppCompatActivity {
    final static String LOGIN_URL = "http://61.164.158.234:8080/angelFor/user?login";
    final static String USER_URL = "http://61.164.158.234:8080/angelFor/user?getNick";
    final static String SMS_URL = "http://61.164.158.234:8080/angelFor/user?sendPhone";
    final static String PASSWORD_URL = "http://61.164.158.234:8080/angelFor/user?foegetPassword";
    Dialog loginDialog ;
    Dialog forgetPasswordDialog;
    private SharedPreferences sp;
    private boolean isSendCodeEnable = true;
    public static LoginActivity _this ;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 隐藏标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //setContentView(R.layout.activity_start);
       // openLoginDialog();
        setContentView(R.layout.activity_login);

        //login();
       // setting();
       // bulid();

        checkIsLogin();
        _this = this;
       // openLoginDialog();

        //newBuild();
    }

    public void checkIsLogin(){
        sp = getSharedPreferences("userInfo", 0);
        String token =sp.getString("token", "");
        if(token.length()>0){
            getUserInfo(token);

        }else{
            openLoginDialog();
        }


    }



    public void openLoginDialog(){
        // Toast.makeText(this, "Button clicked!", Toast.LENGTH_SHORT).show();
        if(loginDialog==null) {
            loginDialog = new Dialog(LoginActivity.this);
            //Dialog dialog = new AlertDialog.Builder(LoginActivity.this).create();
            loginDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            loginDialog.setContentView(R.layout.dialog_login);
            loginDialog.getWindow().setWindowAnimations(R.style.DialogBottom);
            // dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            loginDialog.getWindow().setBackgroundDrawable(new ColorDrawable());
            loginDialog.setCancelable(false);

        }

        loginDialog.show();
    }

    public void opeonForgetPasswordDialog(View view){
        loginDialog.hide();
        if(forgetPasswordDialog==null){
            forgetPasswordDialog=  new Dialog(this);
            forgetPasswordDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            forgetPasswordDialog.setContentView(R.layout.dialog_password_forget);

            forgetPasswordDialog.getWindow().setBackgroundDrawable(new ColorDrawable());
            forgetPasswordDialog.setCancelable(false);

        }
        forgetPasswordDialog.show();

    }

    public void jumpToMain(){
        Intent i = new Intent();
        i.setClass(LoginActivity.this, MainActivity.class);
        startActivity(i);

    }

    public  void jumpToLoginDialog(View view){
        forgetPasswordDialog.hide();
        loginDialog.show();
    }

    public void onCodeBtnClick(View view){
        if(!isSendCodeEnable){
            ToastUtils.show(LoginActivity.this,"一分钟后可重新发送");
            return;
        }
        EditText inputPhone = (EditText)forgetPasswordDialog.findViewById(R.id.password_forget_phone);
        String phone = inputPhone.getText().toString();
        if(phone.isEmpty()){
            ToastUtils.show(LoginActivity.this,"请填写手机号码");
        }
        sendSms(phone);
    }
    public void statCountDown(){
        isSendCodeEnable = false;
        Timer timer=new Timer();
        TimerTask task=new TimerTask()
        {
            @Override
            public void run(){
                //final Intent intent=new Intent(this,LoginActivity.class);
                isSendCodeEnable = true;
            }
        };
        timer.schedule(task,60000);
    }


    public void sendSms(String phone){
        //加载网络数据
        OkHttpUtils
                .post()
                .url(SMS_URL)
                .addParams("phoneNum", phone)
                .build()
                .execute(new JsonCallback<SmsModel>(SmsModel.class) {
                    @Override
                    public void onResponse(final SmsModel response,int id) {

                        if (response == null) {
                            ToastUtils.show(LoginActivity.this,"数据错误");
                            return;
                        }else if(!response.isSuccess()){
                            ToastUtils.show(LoginActivity.this,response.getMessage());
                            return;
                        }
                        ToastUtils.show(LoginActivity.this,response.getMessage());
                        statCountDown();
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("error",e.toString());
                        ToastUtils.show(LoginActivity.this,"网络错误");
                        return;
                    }
                });
    }

    public void forgetPasswordSubmit(View view){
        //获取信息
        EditText inputPhone = (EditText)forgetPasswordDialog.findViewById(R.id.password_forget_phone);
        EditText inputCode = (EditText)forgetPasswordDialog.findViewById(R.id.password_forget_code);
        EditText inputPassword = (EditText)forgetPasswordDialog.findViewById(R.id.password_forget_password_new);
        String phone = inputPhone.getText().toString();
        String code = inputCode.getText().toString();
        String  password = inputPassword.getText().toString();




        OkHttpUtils
                .post()
                .url(PASSWORD_URL)
                .addParams("userId", phone)
                .addParams("code", code)
                .addParams("newPassword", password)
                .build()
                .execute(new JsonCallback<ForgetPasswordModel>(ForgetPasswordModel.class) {
                    @Override
                    public void onResponse(final ForgetPasswordModel response,int id) {

                        if (response == null) {
                            ToastUtils.show(LoginActivity.this,"数据错误");
                            return;
                        }else if(!response.isSuccess()){
                            ToastUtils.show(LoginActivity.this,response.getMessage());
                            return;
                        }
                        ToastUtils.show(LoginActivity.this,response.getMessage());

                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("error",e.toString());
                        ToastUtils.show(LoginActivity.this,"网络错误");
                        return;
                    }
                });
    }




    public void getToken(String username,String password){

        OkHttpUtils
                .post()
                .url(LOGIN_URL)
                .addParams("userId", username)
                .addParams("password", password)
                .build()
                .execute(new JsonCallback<TokenModel>(TokenModel.class) {
                    @Override
                    public void onResponse(final TokenModel response,int id) {
                        if (response == null) {
                            ToastUtils.show(LoginActivity.this,"数据错误");
                            return;
                        }else if(!response.isSuccess()){
                            ToastUtils.show(LoginActivity.this,response.getMessage());
                            return;
                        }
                        //获取用户信息
                        getUserInfo(response.getToken());
                    }

                    @Override
                    public void onError(Call call, Exception e,int id) {
                        Log.e("error",e.toString());
                        ToastUtils.show(LoginActivity.this,"网络错误");
                        return;
                    }
                });
    }

    public void getUserInfo(final String token){
        OkHttpUtils
                .post()
                .url(USER_URL)
                .addParams("token", token)
                 .build()
                .execute(new JsonCallback<UserModel>(UserModel.class) {
                    @Override
                    public void onResponse(final UserModel response,int id) {
                        if (response == null) {
                            ToastUtils.show(LoginActivity.this,"数据错误");
                            return;
                        }else if(!response.isSuccess()){
                            ToastUtils.show(LoginActivity.this,response.getMessage());
                            //开始弹框
                            openLoginDialog();
                            return;
                        }else if(response.getNickName()==null){
                            ToastUtils.show(LoginActivity.this,"用户信息丢失");
                            //开始弹框
                            openLoginDialog();
                            return;
                        }
                        sp = getSharedPreferences("userInfo", 0);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("token",token);
                        editor.commit();
                        CommonUtils.setToken(token);
                        CommonUtils.setCurrentUser(response);
                        //保存用户信息
                        //getUserInfo(response.getToken());
                        jumpToMain();
                    }

                    @Override
                    public void onError(Call call, Exception e,int id) {
                        Log.e("error",e.toString());
                        ToastUtils.show(LoginActivity.this,"网络错误");
                        return;
                    }
                });
    }



    public void login(View view){

        EditText usernameInput =  (EditText)loginDialog.findViewById(R.id.username);
        EditText passwordInput =  (EditText)loginDialog.findViewById(R.id.password);
        String username = usernameInput.getText().toString();
        String password = passwordInput.getText().toString();

        getToken(username,password);


    }


}
